<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
  <head>
    <meta charset="utf-8" />
    <meta name="generator" content="pandoc" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, user-scalable=yes"
    />
    <title>python-basics</title>
    <style type="text/css">
      code {
        white-space: pre-wrap;
      }
      span.smallcaps {
        font-variant: small-caps;
      }
      span.underline {
        text-decoration: underline;
      }
      div.column {
        display: inline-block;
        vertical-align: top;
        width: 50%;
      }
    </style>
  </head>
  <body>
    <h1 id="notes"><strong>Notes</strong></h1>
    <h2 id="basics"><strong>Basics</strong></h2>
    <ul>
      <li>
        <p>
          <strong>PEP8</strong> : Python Enhancement Proposals, style-guide for
          Python.
        </p>
      </li>
      <li>
        <p><code>print</code> is the equivalent of <code>console.log</code>.</p>
      </li>
      <li>
        <p><code>#</code> is used to make comments in your code.</p>
        <p>
          def foo(): """ The foo function does many amazing things that you
          should not question. Just accept that it exists and use it with
          caution. """ secretThing()
        </p>
      </li>
      <li>
        <p>
          Python has a built in help function that let’s you see a description
          of the source code without having to navigate to it.
        </p>
      </li>
    </ul>
    <hr />
    <h2 id="numbers"><strong>Numbers</strong></h2>
    <ul>
      <li>
        <p>Python has three types of numbers:</p>
        <ul>
          <li>
            <p><strong>Integer</strong></p>
            <ul>
              <li>Positive and Negative Counting Numbers.</li>
              <li>No Decimal Point</li>
              <li>
                <p>
                  Created by a literal non-decimal pt number or with the
                  <code>int()</code> constructor.
                </p>
                <p>
                  print(3) # =&gt; 3 print(int(19)) # =&gt; 19 print(int()) #
                  =&gt; 0
                </p>
              </li>
            </ul>
            <blockquote>
              <p>Boolean is a subtype of integer in Python.</p>
            </blockquote>
          </li>
          <li>
            <p><strong>Floating Point Number</strong></p>
            <ul>
              <li>
                <p>Decimal Numbers.</p>
                <p>
                  print(2.24) # =&gt; 2.24 print(2.) # =&gt; 2.0 print(float())
                  # =&gt; 0.0 print(27e-5) # =&gt; 0.00027
                </p>
              </li>
            </ul>
          </li>
          <li>
            <p><strong>Complex Numbers</strong></p>
            <ul>
              <li>Consist of a real part and imaginary part.</li>
              <li>
                <p>
                  The <code>i</code> is switched to a <code>j</code> in
                  programming.
                </p>
                <p>
                  print(7j) # =&gt; 7j print(5.1+7.7j)) # =&gt; 5.1+7.7j
                  print(complex(3, 5)) # =&gt; 3+5j print(complex(17)) # =&gt;
                  17+0j print(complex()) # =&gt; 0j
                </p>
              </li>
            </ul>
          </li>
        </ul>
      </li>
      <li>
        <p>
          <strong>Type Casting</strong> : The process of converting one number
          to another.
        </p>
        <h1 id="using-float">Using Float</h1>
        <p>print(17) # =&gt; 17 print(float(17)) # =&gt; 17.0</p>
        <h1 id="using-int">Using Int</h1>
        <p>print(17.0) # =&gt; 17.0 print(int(17.0)) # =&gt; 17</p>
        <h1 id="using-str">Using Str</h1>
        <p>print(str(17.0) + ’ and ’ + str(17)) # =&gt; 17.0 and 17</p>
      </li>
      <li>
        <p>
          The arithmetic operators are the same between JS and Python, with two
          additions:
        </p>
        <ul>
          <li>“**” : Double asterisk for exponent.</li>
          <li>“//” : Integer Division.</li>
        </ul>
      </li>
      <li><p>There are no spaces between math operations in Python.</p></li>
      <li>
        <p>
          Integer Division gives the other part of the number from Module; it is
          a way to do round down numbers replacing <code>Math.floor()</code> in
          JS.
        </p>
      </li>
      <li>
        There are no <code>++</code> and <code>--</code> in Python, the only
        shorthand operators are:
      </li>
      <li>
        <figure>
          <img
            src="https://i.gyazo.com/745b12d4b84304462e53a69d8492c58d.png"
            alt="pic"
          />
          <figcaption>pic</figcaption>
        </figure>
      </li>
    </ul>
    <hr />
    <h2 id="strings"><strong>Strings</strong></h2>
    <ul>
      <li><p>Python uses both single and double quotes.</p></li>
      <li>
        <p>
          You can escape strings like so
          <code>'Jodi asked, "What\'s up, Sam?"'</code>
        </p>
      </li>
      <li>
        <p>Multiline strings use triple quotes.</p>
        <p>
          print(’‘’My instructions are very long so to make them more readable
          in the code I am putting them on more than one line. I can even
          include “quotes” of any kind because they won’t get confused with the
          end of the string!’’’)
        </p>
      </li>
      <li>
        <p>
          Use the <code>len()</code> function to get the length of a string.
        </p>
        <pre><code>print(len(&quot;Spaghetti&quot;))    # =&gt; 9</code></pre>
      </li>
      <li>Python uses <code>zero-based indexing</code></li>
      <li>
        <p>Python allows negative indexing (thank god!)</p>
        <pre><code>print(&quot;Spaghetti&quot;[-1])    # =&gt; i
print(&quot;Spaghetti&quot;[-4])    # =&gt; e</code></pre>
      </li>
      <li>
        <p>Python let’s you use ranges</p>
        <pre><code>print(&quot;Spaghetti&quot;[1:4])  # =&gt; pag
print(&quot;Spaghetti&quot;[4:-1])    # =&gt; hett
print(&quot;Spaghetti&quot;[4:4])  # =&gt; (empty string)</code></pre>
        <ul>
          <li>
            The end range is exclusive just like <code>slice</code> in JS.
          </li>
        </ul>
        <h1
          id="shortcut-to-get-from-the-beginning-of-a-string-to-a-certain-index."
        >
          Shortcut to get from the beginning of a string to a certain index.
        </h1>
        <p>
          print(“Spaghetti”[:4]) # =&gt; Spag print(“Spaghetti”[:-1]) # =&gt;
          Spaghett
        </p>
        <h1 id="shortcut-to-get-from-a-certain-index-to-the-end-of-a-string.">
          Shortcut to get from a certain index to the end of a string.
        </h1>
        <p>
          print(“Spaghetti”[1:]) # =&gt; paghetti print(“Spaghetti”[-4:]) #
          =&gt; etti
        </p>
      </li>
      <li>
        <p>
          The <code>index</code> string function is the equiv. of
          <code>indexOf()</code> in JS
        </p>
        <p>
          print(“Spaghetti”.index(“h”)) # =&gt; 4 print(“Spaghetti”.index(“t”))
          # =&gt; 6
        </p>
      </li>
      <li>
        <p>
          The <code>count</code> function finds out how many times a substring
          appears in a string.
        </p>
        <p>
          print(“Spaghetti”.count(“h”)) # =&gt; 1 print(“Spaghetti”.count(“t”))
          # =&gt; 2 print(“Spaghetti”.count(“s”)) # =&gt; 0 print(’‘’We choose
          to go to the moon in this decade and do the other things, not because
          they are easy, but because they are hard, because that goal will serve
          to organize and measure the best of our energies and skills, because
          that challenge is one that we are willing to accept, one we are
          unwilling to postpone, and one which we intend to win, and the others,
          too.’’‘.count(’the’)) # =&gt; 4
        </p>
      </li>
      <li>
        <p>
          You can use <code>+</code> to concatenate strings, just like in JS.
        </p>
      </li>
      <li>
        <p>You can also use “*” to repeat strings or multiply strings.</p>
      </li>
      <li>
        <p>
          Use the <code>format()</code> function to use placeholders in a string
          to input values later on.
        </p>
        <p>
          first_name = “Billy” last_name = “Bob” print(‘Your name is {0}
          {1}’.format(first_name, last_name)) # =&gt; Your name is Billy Bob
        </p>
      </li>
      <li>
        <p>
          Shorthand way to use format function is:
          <code>print(f'Your name is {first_name} {last_name}')</code>
        </p>
      </li>
      <li>
        <p>Some useful string methods.</p>
        <ul>
          <li>
            Note that in JS <code>join</code> is used on an Array, in Python it
            is used on String.
            <img
              src="https://i.gyazo.com/ed5094aa444e325b59ec3a11393b60f2.png"
              alt="pic"
            />
          </li>
        </ul>
      </li>
      <li>
        <p>
          There are also many handy testing methods.
          <img
            src="https://i.gyazo.com/af6244c64c06827fb19ac9cd86a75d17.png"
            alt="pic"
          />
        </p>
      </li>
    </ul>
    <hr />
    <h2 id="variables-and-expressions">
      <strong>Variables and Expressions</strong>
    </h2>
    <ul>
      <li>
        <p>
          <strong>Duck-Typing</strong> : Programming Style which avoids checking
          an object’s type to figure out what it can do.
        </p>
        <ul>
          <li>Duck Typing is the fundamental approach of Python.</li>
        </ul>
      </li>
      <li>
        <p>Assignment of a value automatically declares.</p>
        <p>a = 7 b = ‘Marbles’ print(a) # =&gt; 7 print(b) # =&gt; Marbles</p>
      </li>
      <li>
        <p>
          You can chain variable assignments to give multiple var names the same
          value.
        </p>
        <ul>
          <li>Use with caution as this is highly unreadable</li>
        </ul>
        <p>
          count = max = min = 0 print(count) # =&gt; 0 print(max) # =&gt; 0
          print(min) # =&gt; 0
        </p>
      </li>
      <li>
        <p>The value and type of a variable can be re-assigned at any time.</p>
        <p>
          a = 17 print(a) # =&gt; 17 a = ‘seventeen’ print(a) # =&gt; seventeen
        </p>
      </li>
      <li>
        <p>
          <code>NaN</code> does not exist in Python, but you can ‘create’ it
          like so: <code>print(float("nan"))</code>
        </p>
      </li>
      <li>
        Python replaces <code>null</code> with <code>none</code>.
        <ul>
          <li>
            <code>none</code> is an object and can be directly assigned to a
            variable.
          </li>
          <li>
            Using none is a convenient way to check to see why an action may not
            be operating correctly in your program.
          </li>
        </ul>
      </li>
    </ul>
    <hr />
    <h2 id="boolean-data-type"><strong>Boolean Data Type</strong></h2>
    <ul>
      <li>
        <p>
          One of the biggest benefits of Python is that it reads more like
          English than JS does.
          <img
            src="https://i.gyazo.com/3d9fb881df9245a42024aae4ee38a1c5.png"
            alt="pic"
          />
        </p>
        <h1 id="logical-and">Logical AND</h1>
        <p>
          print(True and True) # =&gt; True print(True and False) # =&gt; False
          print(False and False) # =&gt; False
        </p>
        <h1 id="logical-or">Logical OR</h1>
        <p>
          print(True or True) # =&gt; True print(True or False) # =&gt; True
          print(False or False) # =&gt; False
        </p>
        <h1 id="logical-not">Logical NOT</h1>
        <p>
          print(not True) # =&gt; False print(not False and True) # =&gt; True
          print(not True or False) # =&gt; False
        </p>
      </li>
      <li>
        <p>
          By default, Python considers an object to be true UNLESS it is one of
          the following:
        </p>
        <ul>
          <li>Constant <code>None</code> or <code>False</code></li>
          <li>Zero of any numeric type.</li>
          <li>Empty Sequence or Collection.</li>
        </ul>
      </li>
      <li>
        <p><code>True</code> and <code>False</code> must be capitalized</p>
      </li>
    </ul>
    <hr />
    <h2 id="comparison-operators"><strong>Comparison Operators</strong></h2>
    <ul>
      <li><p>Python uses all the same equality operators as JS.</p></li>
      <li>
        <p>In Python, equality operators are processed from left to right.</p>
      </li>
      <li>
        <p>Logical operators are processed in this order:</p>
        <ol type="1">
          <li><strong>NOT</strong></li>
          <li><strong>AND</strong></li>
          <li><strong>OR</strong></li>
        </ol>
      </li>
      <li>
        <p>
          Just like in JS, you can use <code>parentheses</code> to change the
          inherent order of operations.
        </p>
      </li>
      <li>
        <p>
          <strong>Short Circuit</strong> : Stopping a program when a
          <code>true</code> or <code>false</code> has been reached.
          <img
            src="https://i.gyazo.com/ccbe5511757813a61e3833d13c43fd8b.png"
            alt="pic"
          />
        </p>
      </li>
    </ul>
    <hr />
    <h2 id="identity-vs-equality"><strong>Identity vs Equality</strong></h2>
    <pre><code>print (2 == &#39;2&#39;)    # =&gt; False
print (2 is &#39;2&#39;)    # =&gt; False

print (&quot;2&quot; == &#39;2&#39;)    # =&gt; True
print (&quot;2&quot; is &#39;2&#39;)    # =&gt; True

# There is a distinction between the number types.
print (2 == 2.0)    # =&gt; True
print (2 is 2.0)    # =&gt; False</code></pre>
    <ul>
      <li>
        In the Python community it is better to use <code>is</code> and
        <code>is not</code> over <code>==</code> or <code>!=</code>
      </li>
    </ul>
    <hr />
    <h2 id="if-statements"><strong>If Statements</strong></h2>
    <pre><code>if name == &#39;Monica&#39;:
    print(&#39;Hi, Monica.&#39;)

if name == &#39;Monica&#39;:
    print(&#39;Hi, Monica.&#39;)
else:
    print(&#39;Hello, stranger.&#39;)

if name == &#39;Monica&#39;:
    print(&#39;Hi, Monica.&#39;)
elif age &lt; 12:
    print(&#39;You are not Monica, kiddo.&#39;)
elif age &gt; 2000:
   print(&#39;Unlike you, Monica is not an undead, immortal vampire.&#39;)
elif age &gt; 100:
   print(&#39;You are not Monica, grannie.&#39;)</code></pre>
    <ul>
      <li>Remember the order of <code>elif</code> statements matter.</li>
    </ul>
    <hr />
    <h2 id="while-statements"><strong>While Statements</strong></h2>
    <pre><code>spam = 0
while spam &lt; 5:
  print(&#39;Hello, world.&#39;)
  spam = spam + 1</code></pre>
    <ul>
      <li>
        <p><code>Break</code> statement also exists in Python.</p>
        <p>
          spam = 0 while True: print(‘Hello, world.’) spam = spam + 1 if spam
          &gt;= 5: break
        </p>
      </li>
      <li>
        <p>As are <code>continue</code> statements</p>
        <p>
          spam = 0 while True: print(‘Hello, world.’) spam = spam + 1 if spam
          &lt; 5: continue break
        </p>
      </li>
    </ul>
    <hr />
    <h2 id="tryexcept-statements"><strong>Try/Except Statements</strong></h2>
    <ul>
      <li>
        <p>Python equivalent to <code>try/catch</code></p>
        <p>
          a = 321 try: print(len(a)) except: print(‘Silently handle error here’)
        </p>
        <pre><code># Optionally include a correction to the issue
a = str(a)
print(len(a)</code></pre>
        <p>
          a = ‘321’ try: print(len(a)) except: print(‘Silently handle error
          here’)
        </p>
        <pre><code># Optionally include a correction to the issue
a = str(a)
print(len(a))</code></pre>
      </li>
      <li>
        <p>You can name an error to give the output more specificity.</p>
        <p>
          a = 100 b = 0 try: c = a / b except ZeroDivisionError: c = None
          print(c)
        </p>
      </li>
      <li>
        <p>
          You can also use the <code>pass</code> commmand to by pass a certain
          error.
        </p>
        <p>a = 100 b = 0 try: print(a / b) except ZeroDivisionError: pass</p>
      </li>
      <li>
        <p>
          The <code>pass</code> method won’t allow you to bypass every single
          error so you can chain an exception series like so:
        </p>
        <p>a = 100</p>
        <h1 id="b-5">b = “5”</h1>
        <p>
          try: print(a / b) except ZeroDivisionError: pass except (TypeError,
          NameError): print(“ERROR!”)
        </p>
      </li>
      <li>
        <p>
          You can use an <code>else</code> statement to end a chain of
          <code>except</code> statements.
        </p>
        <h1 id="tuple-of-file-names">tuple of file names</h1>
        <p>files = (‘one.txt’, ‘two.txt’, ‘three.txt’)</p>
        <h1 id="simple-loop">simple loop</h1>
        <p>
          for filename in files: try: # open the file in read mode f =
          open(filename, ‘r’) except OSError: # handle the case where file does
          not exist or permission is denied print(‘cannot open file’, filename)
          else: # do stuff with the file object (f) print(filename, ‘opened
          successfully’) print(‘found’, len(f.readlines()), ‘lines’) f.close()
        </p>
      </li>
      <li>
        <p>
          <code>finally</code> is used at the end to clean up all actions under
          any circumstance.
        </p>
        <p>
          def divide(x, y): try: result = x / y except ZeroDivisionError:
          print(“Cannot divide by zero”) else: print(“Result is”, result)
          finally: print(“Finally…”)
        </p>
      </li>
      <li>
        <p>
          Using duck typing to check to see if some value is able to use a
          certain method.
        </p>
        <h1 id="try-a-number---nothing-will-print-out">
          Try a number - nothing will print out
        </h1>
        <p>a = 321 if hasattr(a, ‘<strong>len</strong>’): print(len(a))</p>
        <h1 id="try-a-string---the-length-will-print-out-4-in-this-case">
          Try a string - the length will print out (4 in this case)
        </h1>
        <p>b = “5555” if hasattr(b, ‘<strong>len</strong>’): print(len(b))</p>
      </li>
    </ul>
    <hr />
    <h2 id="pass"><strong>Pass</strong></h2>
    <ul>
      <li>
        <p>Pass Keyword is required to write the JS equivalent of :</p>
        <p>if (true) { }</p>
        <p>while (true) {}</p>
        <p>if True: pass</p>
        <p>while True: pass</p>
      </li>
    </ul>
    <hr />
    <h2 id="functions"><strong>Functions</strong></h2>
    <ul>
      <li>
        <p><strong>Function</strong> definition includes:</p>
        <ul>
          <li>The <code>def</code> keyword</li>
          <li>The name of the function</li>
          <li>A list of parameters enclosed in parentheses.</li>
          <li>A colon at the end of the line.</li>
          <li>One tab indentation for the code to run.</li>
        </ul>
      </li>
      <li>
        <p>You can use default parameters just like in JS</p>
        <p>def greeting(name, saying=“Hello”): print(saying, name)</p>
        <p>greeting(“Monica”)</p>
        <h1 id="hello-monica">Hello Monica</h1>
        <p>greeting(“Barry”, “Hey”)</p>
        <h1 id="hey-barry">Hey Barry</h1>
      </li>
      <li>
        <p>
          Keep in mind, default parameters must always come after regular
          parameters.
        </p>
        <h1 id="this-is-bad-code-and-will-not-run">
          THIS IS BAD CODE AND WILL NOT RUN
        </h1>
        <p>def increment(delta=1, value): return delta + value</p>
      </li>
      <li>
        <p>
          You can specify arguments by name without destructuring in Python.
        </p>
        <p>def greeting(name, saying=“Hello”): print(saying, name)</p>
        <h1 id="name-has-no-default-value-so-just-provide-the-value">
          name has no default value, so just provide the value
        </h1>
        <h1 id="saying-has-a-default-value-so-use-a-keyword-argument">
          saying has a default value, so use a keyword argument
        </h1>
        <p>greeting(“Monica”, saying=“Hi”)</p>
      </li>
      <li>
        <p>
          The <code>lambda</code> keyword is used to create anonymous functions
          and are supposed to be <code>one-liners</code>.
        </p>
      </li>
    </ul>
    <p><code>toUpper = lambda s: s.upper()</code></p>
    <hr />
    <p>
      Notes Formatted Strings Remember that in Python join() is called on a
      string with an array/list passed in as the argument. shopping_list =
      [‘bread’,‘milk’,‘eggs’] print(‘,’.join(shopping_list)) Python has a very
      powerful formatting engine. format() is also applied directly to strings.
    </p>
    <h1 id="comma-thousands-separator">Comma Thousands Separator</h1>
    <p>print(‘{:,}’.format(1234567890)) ‘1,234,567,890’</p>
    <h1 id="date-and-time">Date and Time</h1>
    <p>
      d = datetime.datetime(2020, 7, 4, 12, 15, 58) print(‘{:%Y-%m-%d
      %H:%M:%S}’.format(d)) ‘2020-07-04 12:15:58’
    </p>
    <h1 id="percentage">Percentage</h1>
    <p>
      points = 190 total = 220 print(‘Correct answers:
      {:.2%}’.format(points/total)) Correct answers: 86.36%
    </p>
    <h1 id="data-tables">Data Tables</h1>
    <p>
      width=8 print(’ decimal hex binary’) print(‘-’*27) for num in range(1,16):
      for base in ‘dXb’: print(‘{0:{width}{base}}’.format(num, base=base,
      width=width), end=’ ‘) print() Getting Input from the Command Line Python
      runs synchronously, all programs and processes will stop when listening
      for a user input. The input function shows a prompt to a user and waits
      for them to type ’ENTER’. Scripts vs Programs Programming Script : A set
      of code that runs in a linear fashion. The largest difference between
      scripts and programs is the level of complexity and purpose. Programs
      typically have many UI’s.
    </p>
    <p>
      Python can be used to display html, css, and JS. We will be using Python
      as an API (Application Programming Interface)
    </p>
    <p>
      Structured Data Sequence : The most basic data structure in Python where
      the index determines the order.
    </p>
    <p>
      List Tuple Range Collections : Unordered data structures, hashable values.
    </p>
    <p>
      Dictionaries Sets Iterable : Generic name for a sequence or collection;
      any object that can be iterated through. Can be mutable or immutable.
      Built In Data Types Lists are the python equivalent of arrays. empty_list
      = [] departments = [‘HR’,‘Development’,‘Sales’,‘Finance’,‘IT’,‘Customer
      Support’]
    </p>
    <h1 id="you-can-instantiate">You can instantiate</h1>
    <p>specials = list()</p>
    <h1 id="test-if-a-value-is-in-a-list.">Test if a value is in a list.</h1>
    <p>
      print(1 in [1, 2, 3]) #&gt; True print(4 in [1, 2, 3]) #&gt; False Tuples
      : Very similar to lists, but they are immutable
    </p>
    <h1 id="instantiated-with-parentheses">Instantiated with parentheses</h1>
    <p>time_blocks = (‘AM’,‘PM’)</p>
    <h1 id="sometimes-instantiated-without">Sometimes instantiated without</h1>
    <p>colors = ‘red’,‘blue’,‘green’ numbers = 1, 2, 3</p>
    <h1 id="tuple-built-in-can-be-used-to-convert-other-data-into-a-tuple">
      Tuple() built in can be used to convert other data into a tuple
    </h1>
    <p>
      tuple(‘abc’) # returns (‘a’, ‘b’, ‘c’) tuple([1,2,3]) # returns (1, 2, 3)
      Think of tuples as constant variables.
    </p>
    <p>
      Ranges : A list of numbers which can’t be changed; often used with for
      loops. Declared using one to three parameters. Start : opt. default 0,
      first # in sequence. Stop : required next number past the last number in
      the sequence. Step : opt. default 1, difference between each number in the
      sequence. range(5) # [0, 1, 2, 3, 4] range(1,5) # [1, 2, 3, 4] range(0,
      25, 5) # [0, 5, 10, 15, 20] range(0) # [ ] for let (i = 0; i &lt; 5; i++)
      for let (i = 1; i &lt; 5; i++) for let (i = 0; i &lt; 25; i+=5) for let(i
      = 0; i = 0; i++) Keep in mind that stop is not included in the range.
    </p>
    <p>
      Dictionaries : Mappable collection where a hashable value is used as a key
      to ref. an object stored in the dictionary. Mutable. a = {‘one’:1,
      ‘two’:2, ‘three’:3} b = dict(one=1, two=2, three=3) c = dict([(‘two’, 2),
      (‘one’, 1), (‘three’, 3)]) a, b, and c are all equal
    </p>
    <p>Declared with curly braces of the built in dict()</p>
    <p>
      Benefit of dictionaries in Python is that it doesn’t matter how it is
      defined, if the keys and values are the same the dictionaries are
      considered equal.
    </p>
    <p>Use the in operator to see if a key exists in a dictionary.</p>
    <p>
      Sets : Unordered collection of distinct objects; objects that need to be
      hashable.
    </p>
    <p>
      Always be unique, duplicate items are auto dropped from the set. Common
      Uses: Removing Duplicates Membership Testing Mathematical Operators:
      Intersection, Union, Difference, Symmetric Difference. Standard Set is
      mutable, Python has a immutable version called frozenset. Sets created by
      putting comma seperated values inside braces:
    </p>
    <p>
      school_bag =
      {‘book’,‘paper’,‘pencil’,‘pencil’,‘book’,‘book’,‘book’,‘eraser’}
      print(school_bag)
    </p>
    <h1 id="also-can-use-set-constructor-to-automatically-put-it-into-a-set.">
      Also can use set constructor to automatically put it into a set.
    </h1>
    <p>
      letters = set(‘abracadabra’) print(letters) Built-In Functions Functions
      using iterables
    </p>
    <p>
      filter(function, iterable) : creates new iterable of the same type which
      includes each item for which the function returns true.
    </p>
    <p>
      map(function, iterable) : creates new iterable of the same type which
      includes the result of calling the function on every item of the iterable.
    </p>
    <p>
      sorted(iterable, key=None, reverse=False) : creates a new sorted list from
      the items in the iterable.
    </p>
    <p>
      Output is always a list key: opt function which coverts and item to a
      value to be compared. reverse: optional boolean. enumerate(iterable,
      start=0) : starts with a sequence and converts it to a series of tuples
    </p>
    <p>
      quarters = [‘First’, ‘Second’, ‘Third’, ‘Fourth’]
      print(enumerate(quarters)) print(enumerate(quarters, start=1))
    </p>
    <h1 id="first-1-second-2-third-3-fourth">
      (0, ‘First’), (1, ‘Second’), (2, ‘Third’), (3, ‘Fourth’)
    </h1>
    <h1 id="first-2-second-3-third-4-fourth">
      (1, ‘First’), (2, ‘Second’), (3, ‘Third’), (4, ‘Fourth’)
    </h1>
    <p>
      zip(*iterables) : creates a zip object filled with tuples that combine 1
      to 1 the items in each provided iterable. Functions that analyze iterables
    </p>
    <p>len(iterable) : returns the count of the number of items.</p>
    <p>max(*args, key=None) : returns the largest of two or more arguments.</p>
    <p>max(iterable, key=None) : returns the largest item in the iterable.</p>
    <p>
      key optional function which converts an item to a value to be compared.
      min works the same way as max
    </p>
    <p>sum(iterable) : used with a list of numbers to generate the total.</p>
    <p>
      There is a faster way to concatenate an array of strings into one string,
      so do not use sum for that. any(iterable) : returns True if any items in
      the iterable are true.
    </p>
    <p>all(iterable) : returns True is all items in the iterable are true.</p>
    <p>Working with dictionaries</p>
    <p>
      dir(dictionary) : returns the list of keys in the dictionary. Working with
      sets
    </p>
    <p>
      Union : The pipe | operator or union(*sets) function can be used to
      produce a new set which is a combination of all elements in the provided
      set. a = {1, 2, 3} b = {2, 4, 6} print(a | b) # =&gt; {1, 2, 3, 4, 6}
      Intersection : The &amp; operator ca be used to produce a new set of only
      the elements that appear in all sets. a = {1, 2, 3} b = {2, 4, 6} print(a
      &amp; b) # =&gt; {2} Difference : The - operator can be used to produce a
      new set of only the elements that appear in the first set and NOT the
      others.
    </p>
    <p>
      Symmetric Difference : The ^ operator can be used to produce a new set of
      only the elements that appear in exactly one set and not in both.
    </p>
    <p>
      a = {1, 2, 3} b = {2, 4, 6} print(a - b) # =&gt; {1, 3} print(b - a) #
      =&gt; {4, 6} print(a ^ b) # =&gt; {1, 3, 4, 6} For Statements In python,
      there is only one for loop.
    </p>
    <p>
      Always Includes: The for keyword A variable name The in keyword An
      iterable of some kid A colon On the next line, an indented block of code
      called the for clause. You can use break and continue statements inside
      for loops as well.
    </p>
    <p>You can use the range function as the iterable for the for loop.</p>
    <p>
      print(‘My name is’) for i in range(5): print(‘Carlita Cinco (’ + str(i) +
      ‘)’)
    </p>
    <p>
      total = 0 for num in range(101): total += num print(total) Looping over a
      list in Python for c in [‘a’, ‘b’, ‘c’]: print(c)
    </p>
    <p>
      lst = [0, 1, 2, 3] for i in lst: print(i) Common technique is to use the
      len() on a pre-defined list with a for loop to iterate over the indices of
      the list. supplies = [‘pens’, ‘staplers’, ‘flame-throwers’, ‘binders’] for
      i in range(len(supplies)): print(‘Index’ + str(i) + ’ in supplies is: ’ +
      supplies[i]) You can loop and destructure at the same time. l = [[1, 2],
      [3, 4], [5, 6]] for a, b in l: print(a, ‘,’, b)
    </p>
    <h1 id="prints-1-2">Prints 1, 2</h1>
    <h1 id="prints-3-4">Prints 3, 4</h1>
    <h1 id="prints-5-6">Prints 5, 6</h1>
    <p>
      You can use values() and keys() to loop over dictionaries. spam =
      {‘color’: ‘red’, ‘age’: 42} for v in spam.values(): print(v)
    </p>
    <h1 id="prints-red">Prints red</h1>
    <h1 id="prints-42">Prints 42</h1>
    <p>for k in spam.keys(): print(k)</p>
    <h1 id="prints-color">Prints color</h1>
    <h1 id="prints-age">Prints age</h1>
    <p>For loops can also iterate over both keys and values.</p>
    <h1 id="getting-tuples">Getting tuples</h1>
    <p>for i in spam.items(): print(i)</p>
    <h1 id="prints-color-red">Prints (‘color’, ‘red’)</h1>
    <h1 id="prints-age-42">Prints (‘age’, 42)</h1>
    <h1 id="destructuring-to-values">Destructuring to values</h1>
    <p>for k, v in spam.items(): print(‘Key:’ + k + ’ Value: ’ + str(v))</p>
    <h1 id="prints-key-age-value-42">Prints Key: age Value: 42</h1>
    <h1 id="prints-key-color-value-red">Prints Key: color Value: red</h1>
    <p>
      Looping over string for c in “abcdefg”: print(c) More On Functions
      Variable-length positional arguments : (<em>args) def add(a, b,</em>
      args): total = a + b; for n in args: total += n return total
    </p>
    <p>add(1, 2) # Returns 3</p>
    <p>
      add(2, 3, 4, 5) # Returns 14 keyword arguments : (*kwargs) def
      print_names_and_countries(greeting, **kwargs): for k, v in kwargs.items():
      print(greeting, k, “from”, v)
    </p>
    <p>
      print_names_and_countries(“Hi”, Monica=“Sweden”, Charles=“British Virgin
      Islands”, Carlo=“Portugal”)
    </p>
    <h1 id="prints">Prints</h1>
    <h1 id="hi-monica-from-sweden">Hi Monica from Sweden</h1>
    <h1 id="hi-charles-from-british-virgin-islands">
      Hi Charles from British Virgin Islands
    </h1>
    <h1 id="hi-carlo-from-portugal">Hi Carlo from Portugal</h1>
    <p>
      When you order arguments within a function or function call, the args need
      to occur in a particular order: formal positional args.
      <em
        >args keyword args with default values **kwargs def example(arg_1,
        arg_2,</em
      >
      args, **kwargs): pass
    </p>
    <p>
      def example2(arg_1, arg_2, *args, kw_1=“shark”, kw_2=“blowfish”,
      **kwargs): pass Importing in Python Modules are similar to packages in
      Node.js Come in different types: Built-In, Third-Party, Custom. All loaded
      using import statements. Terms
    </p>
    <p>
      module : Python code in a separate file. package : Path to a directory
      that contains modules. <strong>init.py</strong> : Default file for a
      package. submodule : Another file in a module’s folder. function :
      Function in a module.
    </p>
    <p>
      A module can be any file but it is usually created by placing a special
      file <strong>init</strong>.py into a folder. pic
    </p>
    <p>Try to avoid importing with wildcards in Python.</p>
    <p>Use multiple lines for clarity when importing.</p>
    <p>
      from urllib.request import ( HTTPDefaultErrorHandler as ErrorHandler,
      HTTPRedirectHandler as RedirectHandler, Request, pathname2url,
      url2pathname, urlopen, ) Watching Out for Python 2 Python 3 removed
      &lt;&gt; and only uses !=
    </p>
    <p>
      format() was introduced with P3 All strings in P3 are unicode and encoded.
      md5 was removed. ConfigParser was renamed to configparser sets were killed
      in favor of set() class.
    </p>
    <p>print was a statement in P2, but is a function in P3.</p>
    <h1 id="topics-revisited-in-python-syntax">
      Topics revisited (in python syntax)
    </h1>
    <pre><code>def say_hi(name):
    &quot;&quot;&quot;&lt;---- Multi-Line Comments and Docstrings
    This is where you put your content for help() to inform the user
    about what your function does and how to use it
    &quot;&quot;&quot;
    print(f&quot;Hello {name}!&quot;)


print(say_hi(&quot;Michael&quot;))  # Should get the print inside the function, then None

# Boolean Values
# Work the same as in JS, except they are title case: True and False
a = True
b = False

# Logical Operators
# ! = not, || = or, &amp;&amp; = and
print(True and True)
print(True and not True)
print(True or True)

# Truthiness - Everything is True except...
# False - None, False, &#39;&#39;, [], (), set(), range(0)

# Number Values
# Integers are numbers without a floating decimal point
print(type(3))  # type returns the type of whatever argument you pass in
# Floating Point values are numbers with a floating decimal point
print(type(3.5))

# Type Casting
# You can convert between ints and floats (along with other types...)
print(float(3))  # If you convert a float to an int, it will truncate the decimal
print(int(4.5))
print(type(str(3)))
# Python does not automatically convert types like JS
# print(17.0 + &#39; heyooo &#39; + 17)  # TypeError

# Arithmetic Operators
# ** - exponent (comparable to Math.pow(num, pow))
# // - integer division
# There is no ++ or -- in Python

# String Values
# We can use single quotes, double quotes, or f&#39;&#39; for string formats
# We can use triple single quotes for multiline strings
print(
    &quot;&quot;&quot;This here&#39;s a story
All about how
My life got twist
Turned upside down
&quot;&quot;&quot;
)

# Three double quotes can also be used, but we typically reserve these for
# multi-line comments and function docstrings (refer to lines 6-9)(Nice :D)
# We use len() to get the length of something
print(len(&quot;Michael&quot;))  # 7 characters
print(len([&quot;hey&quot;, &quot;ho&quot;, &quot;hey&quot;, &quot;hey&quot;, &quot;ho&quot;]))  # 5 list items
print(len({1, 2, 3, 4, 5, 6, 7, 9}))  # 8 set items

# We can index into strings, list, etc..self.
name = &quot;Michael&quot;
for i in range(len(name)):
    print(name[i])  # M, i, c, h, a, e, l

# We can index starting from the end as well, with negatives
occupation = &quot;Full Stack Software Engineer&quot;
print(occupation[-3])  # e

# We can also get ranges in the index with the [start:stop:step] syntax
print(occupation[0:4:1])  # step and stop are optional, stop is exclusive
print(occupation[::4])  # beginning to end, every 4th letter
print(occupation[4:14:2])  # Let&#39;s get weird with it!
# NOTE: Indexing out of range will give you an IndexError

# We can also get the index og things with the .index() method, similar to indexOf()
print(occupation.index(&quot;Stack&quot;))
print([&quot;Mike&quot;, &quot;Barry&quot;, &quot;Cole&quot;, &quot;James&quot;, &quot;Mark&quot;].index(&quot;Cole&quot;))

# We can count how many times a substring/item appears in something as well
print(occupation.count(&quot;S&quot;))
print(
    &quot;&quot;&quot;Now this here&#39;s a story all about how
My life got twist turned upside down
I forget the rest but the the the potato
smells like the potato&quot;&quot;&quot;.count(
        &quot;the&quot;
    )
)

# We concatenate the same as Javascript, but we can also multiply strings
print(&quot;dog &quot; + &quot;show&quot;)
print(&quot;ha&quot; * 10)

# We can use format for a multitude of things, from spaces to decimal places
first_name = &quot;Michael&quot;
last_name = &quot;Shuff&quot;
print(&quot;Your name is {0} {1}&quot;.format(first_name, last_name))

# Useful String Methods
print(&quot;Hello&quot;.upper())  # HELLO
print(&quot;Hello&quot;.lower())  # hello
print(&quot;HELLO&quot;.islower())  # False
print(&quot;HELLO&quot;.isupper())  # True
print(&quot;Hello&quot;.startswith(&quot;he&quot;))  # False
print(&quot;Hello&quot;.endswith(&quot;lo&quot;))  # True
print(&quot;Hello There&quot;.split())  # [Hello, There]
print(&quot;hello1&quot;.isalpha())  # False,  must consist only of letters
print(&quot;hello1&quot;.isalnum())  # True, must consist of only letters and numbers
print(&quot;3215235123&quot;.isdecimal())  # True, must be all numbers
# True, must consist of only spaces/tabs/newlines
print(&quot;       \n     &quot;.isspace())
# False, index 0 must be upper case and the rest lower
print(&quot;MichaeL&quot;.istitle())
print(&quot;Michael Lee&quot;.istitle())  # True!

# Duck Typing - If it walks like a duck, and talks like a duck, it must be a duck
# Assignment - All like JS, but there are no special keywords like let or const
a = 3
b = a
c = &quot;heyoo&quot;
b = [&quot;reassignment&quot;, &quot;is&quot;, &quot;fine&quot;, &quot;G!&quot;]

# Comparison Operators - Python uses the same equality operators as JS, but no ===
# &lt; - Less than
# &gt; - Greater than
# &lt;= - Less than or Equal
# &gt;= - Greater than or Equal
# == - Equal to
# != - Not equal to
# is - Refers to exact same memory location
# not - !
# Precedence - Negative Signs(not) are applied first(part of each number)
#            - Multiplication and Division(and) happen next
#            - Addition and Subtraction(or) are the last step
#  NOTE: Be careful when using not along with ==
print(not a == b)  # True
# print(a == not b) # Syntax Error
print(a == (not b))  # This fixes it. Answer: False
# Python does short-circuit evaluation

# Assignment Operators - Mostly the same as JS except Python has **= and //= (int division)

# Flow Control Statements - if, while, for
# Note: Python smushes &#39;else if&#39; into &#39;elif&#39;!
if 10 &lt; 1:
    print(&quot;We don&#39;t get here&quot;)
elif 10 &lt; 5:
    print(&quot;Nor here...&quot;)
else:
    print(&quot;Hey there!&quot;)

# Looping over a string
for c in &quot;abcdefgh&quot;:
    print(c)

# Looping over a range
for i in range(5):
    print(i + 1)

# Looping over a list
lst = [1, 2, 3, 4]
for i in lst:
    print(i)

# Looping over a dictionary
spam = {&quot;color&quot;: &quot;red&quot;, &quot;age&quot;: 42, &quot;items&quot;: [(1, &quot;hey&quot;), (2, &quot;hooo!&quot;)]}
for v in spam.values():
    print(v)

# Loop over a list of tuples and destructuring the values
# Assuming spam.items returns a list of tuples each containing two items (k, v)
for k, v in spam.items():
    print(f&quot;{k}: {v}&quot;)

# While loops as long as the condition is True
#  - Exit loop early with break
#  - Exit iteration early with continue
spam = 0
while True:
    print(&quot;Heyy girrllll&quot;)
    spam += 1
    if spam &lt; 5:
        continue
    break


# Functions - use def keyword to define a function in Python
def printCopyright():
    print(&quot;Copyright 2020, ya boi, Mike Shuff&quot;)


# Lambdas are one liners! (Should be at least, you can use parenthesis to disobey)
avg = lambda num1, num2: print(num1 + num2)

avg(1, 2)
# Calling it with keyword arguments, order does not matter
avg(num2=20, num1=1252)
printCopyright()

# We can give parameters default arguments like JS
def greeting(name, saying=&quot;Hello&quot;):
    print(saying, name)


greeting(&quot;Mike&quot;)  # Hello Mike
greeting(&quot;Michael&quot;, saying=&quot;Hello there...&quot;)

# A common gotcha is using a mutable object for a default parameter
# All invocations of the function reference the same mutable object
def append_item(item_name, item_list=[]):  # Will it obey and give us a new list?
    item_list.append(item_name)
    return item_list


# Uses same item list unless otherwise stated which is counterintuitive
print(append_item(&quot;notebook&quot;))
print(append_item(&quot;notebook&quot;))
print(append_item(&quot;notebook&quot;, []))

# Errors - Unlike JS, if we pass the incorrect amount of arguments to a function,
#          it will throw an error
# avg(1)  # TypeError
# avg(1, 2, 2) # TypeError

# ----------------------------------- DAY 2 ----------------------------------------
# Functions - * to get rest of position arguments as tuple
#           - ** to get rest of keyword arguments as a dictionary
# Variable Length positional arguments
def add(a, b, *args):
    # args is a tuple of the rest of the arguments
    total = a + b
    for n in args:
        total += n
    return total


print(add(1, 2))  # args is None, returns 3
print(add(1, 2, 3, 4, 5, 6))  # args is (3, 4, 5, 6), returns 21

# Variable Length Keyword Arguments
def print_names_and_countries(greeting, **kwargs):
    # kwargs is a dictionary of the rest of the keyword arguments
    for k, v in kwargs.items():
        print(greeting, k, &quot;from&quot;, v)


print_names_and_countries(
    &quot;Hey there&quot;, Monica=&quot;Sweden&quot;, Mike=&quot;The United States&quot;, Mark=&quot;China&quot;
)

# We can combine all of these together
def example2(arg1, arg2, *args, kw_1=&quot;cheese&quot;, kw_2=&quot;horse&quot;, **kwargs):
    pass


# Lists are mutable arrays
empty_list = []
roomates = [&quot;Beau&quot;, &quot;Delynn&quot;]
# List built-in function makes a list too
specials = list()
# We can use &#39;in&#39; to test if something is in the list, like &#39;includes&#39; in JS
print(1 in [1, 2, 4])  # True
print(2 in [1, 3, 5])  # False

# Dictionaries - Similar to JS POJO&#39;s or Map, containing key value pairs
a = {&quot;one&quot;: 1, &quot;two&quot;: 2, &quot;three&quot;: 3}
b = dict(one=1, two=2, three=3)
# Can use &#39;in&#39; on dictionaries too (for keys)
print(&quot;one&quot; in a)  # True
print(3 in b)  # False

# Sets - Just like JS, unordered collection of distinct objects
bedroom = {&quot;bed&quot;, &quot;tv&quot;, &quot;computer&quot;, &quot;clothes&quot;, &quot;playstation 4&quot;}
# bedroom = set(&quot;bed&quot;, &quot;tv&quot;, &quot;computer&quot;, &quot;clothes&quot;, &quot;playstation 5&quot;)
school_bag = set(
    [&quot;book&quot;, &quot;paper&quot;, &quot;pencil&quot;, &quot;pencil&quot;, &quot;book&quot;, &quot;book&quot;, &quot;book&quot;, &quot;eraser&quot;]
)
print(school_bag)
print(bedroom)
# We can use &#39;in&#39; on sets as wel
print(1 in {1, 2, 3})  # True
print(4 in {1, 3, 5})  # False

# Tuples are immutable lists of items
time_blocks = (&quot;AM&quot;, &quot;PM&quot;)
colors = &quot;red&quot;, &quot;green&quot;, &quot;blue&quot;  # Parenthesis not needed but encouraged
# The tuple built-in function can be used to convert things to tuples
print(tuple(&quot;abc&quot;))
print(tuple([1, 2, 3]))
# &#39;in&#39; may be used on tuples as well
print(1 in (1, 2, 3))  # True
print(5 in (1, 4, 3))  # False

# Ranges are immutable lists of numbers, often used with for loops
#   - start - default: 0, first number in sequence
#   - stop - required, next number past last number in sequence
#   - step - default: 1, difference between each number in sequence
range1 = range(5)  # [0,1,2,3,4]
range2 = range(1, 5)  # [1,2,3,4]
range3 = range(0, 25, 5)  # [0,5,10,15,20]
range4 = range(0)  # []
for i in range1:
    print(i)

# Built-in functions:
# Filter
isOdd = lambda num: num % 2 == 1

filtered = filter(isOdd, [1, 2, 3, 4])
print(list(filtered))
for num in filtered:
    print(f&quot;first way: {num}&quot;)
print(&quot;--&quot; * 20)
[print(f&quot;list comprehension: {i}&quot;) for i in [1, 2, 3, 4, 5, 6, 7, 8] if i % 2 == 1]

# Map
def toUpper(str):
    return str.upper()


upperCased = map(toUpper, [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;])
print(list(upperCased))

# Sorted
sorted_items = sorted([&quot;john&quot;, &quot;tom&quot;, &quot;sonny&quot;, &quot;Mike&quot;])
print(list(sorted_items))  # Notice uppercase comes before lowercase
# Using a key function to control the sorting and make it case insensitive
sorted_items = sorted([&quot;john&quot;, &quot;tom&quot;, &quot;sonny&quot;, &quot;Mike&quot;], key=str.lower)
print(sorted_items)
# You can also reverse the sort
sorted_items = sorted([&quot;john&quot;, &quot;tom&quot;, &quot;sonny&quot;, &quot;Mike&quot;], key=str.lower, reverse=True)
print(sorted_items)

# Enumerate creates a tuple with an index for what you&#39;re enumerating
quarters = [&quot;First&quot;, &quot;Second&quot;, &quot;Third&quot;, &quot;Fourth&quot;]
print(list(enumerate(quarters)))
print(list(enumerate(quarters, start=1)))

# Zip takes list and combines them as key value pairs, or really however you need
keys = (&quot;Name&quot;, &quot;Email&quot;)
values = (&quot;Buster&quot;, &quot;cheetoh@johhnydepp.com&quot;)
zipped = zip(keys, values)
print(list(zipped))
# You can zip more than 2
x_coords = [0, 1, 2, 3, 4]
y_coords = [4, 6, 10, 9, 10]
z_coords = [20, 10, 5, 9, 1]
coords = zip(x_coords, y_coords, z_coords)
print(list(coords))

# Len reports the length of strings along with list and any other object data type
print_len = lambda item: print(len(item))  # doing this to save myself some typing

print_len(&quot;Mike&quot;)
print_len([1, 5, 2, 10, 3, 10])
print_len({1, 5, 10, 9, 10})  # 4 because there is a duplicate here (10)
print_len((1, 4, 10, 9, 20))

# Max will return the max number in a given scenario
print(max(1, 2, 35, 1012, 1))

# Min
print(min(1, 5, 2, 10))
print(min([1, 4, 7, 10]))

# Sum
print(sum([1, 2, 4]))

# Any
print(any([True, False, False]))
print(any([False, False, False]))

# All
print(all([True, True, False]))
print(all([True, True, True]))

# Dir returns all the attributes of an object including it&#39;s methods and dunder methods
user = {&quot;Name&quot;: &quot;Bob&quot;, &quot;Email&quot;: &quot;bob@bob.com&quot;}
print(dir(user))

# Importing packages and modules
#  - Module - A Python code in a file or directory
#  - Package - A module which is a directory containing an __init__.py file
#  - Submodule - A module which is contained within a package
#  - Name - An exported function, class, or variable in a module
# Unlike JS, modules export ALL names contained within them without any special export key

# Assuming we have the following package with four submodules
#  math
#  |  __init__.py
#  | addition.py
#  | subtraction.py
#  | multiplication.py
#  | division.py

# If we peek into the addition.py file we see there&#39;s an add function
# addition.py
# We can import &#39;add&#39; from other places because it&#39;s a &#39;name&#39; and is automatically exported
def add(num1, num2):
    return num1 + num2


# Notice the . syntax because this package can import it&#39;s own submodules.
# Our __init__.py has the following files
# This imports the &#39;add&#39; function
# And now it&#39;s also re-exported in here as well
# from .addition import add
# These import and re-export the rest of the functions from the submodule
# from .subtraction import subtract
# from .division import divide
# from .multiplication import multiply
# So if we have a script.py and want to import add, we could do it many ways

# This will load and execute the &#39;math/__init__.py&#39; file and give
# us an object with the exported names in &#39;math/__init__.py&#39;
import math

# print(math.add(1,2))

# This imports JUST the add from &#39;math/__init__.py&#39;
# from math import add

# print(add(1, 2))

# This skips importing from &#39;math/__init__.py&#39; (although it still runs)
# and imports directly from the addition.py file
# from math.addition import add

# This imports all the functions individually from &#39;math/__init__.py&#39;
# from math import add, subtract, multiply, divide

# print(add(1, 2))
# print(subtract(2, 1))

# This imports &#39;add&#39; renames it to &#39;add_some_numbers&#39;
# from math import add as add_some_numbers

# --------------------------------------- DAY 3 ---------------------------------------
# Classes, Methods, and Properties
class AngryBird:
    # Slots optimize property access and memory usage and prevent you
    # from arbitrarily assigning new properties the instance
    __slots__ = [&quot;_x&quot;, &quot;_y&quot;]

    # Constructor
    def __init__(self, x=0, y=0):
        # Doc String
        &quot;&quot;&quot;
        Construct a new AngryBird by setting it&#39;s position to (0, 0)
        &quot;&quot;&quot;
        ## Instance Variables
        self._x = x
        self._y = y

    # Instance Method
    def move_up_by(self, delta):
        self._y += delta

    # Getter
    @property
    def x(self):
        return self._x

    # Setter
    @x.setter
    def x(self, value):
        if value &lt; 0:
            value = 0
        self._x = value

    @property
    def y(self):
        return self._y

    @y.setter
    def y(self, value):
        self._y = value

    # Dunder Repr... called by &#39;print&#39;
    def __repr__(self):
        return f&quot;&lt;AngryBird ({self._x}, {self._y})&gt;&quot;


# JS to Python Classes cheat table
#        JS                    Python
#   constructor()         def __init__(self):
#      super()            super().__init__()
#   this.property           self.property
#    this.method            self.method()
# method(arg1, arg2){}    def method(self, arg1, ...)
# get someProperty(){}    @property
# set someProperty(){}    @someProperty.setter

# List Comprehensions are a way to transform a list from one format to another
#  - Pythonic Alternative to using map or filter
#  - Syntax of a list comprehension
#     - new_list = [value loop condition]
# Using a for loop
squares = []
for i in range(10):
    squares.append(i ** 2)
print(squares)

# value = i ** 2
# loop = for i in range(10)
squares = [i ** 2 for i in range(10)]
print(list(squares))

sentence = &quot;the rocket came back from mars&quot;
vowels = [character for character in sentence if character in &quot;aeiou&quot;]
print(vowels)

# You can also use them on dictionaries. We can use the items() method
# for the dictionary to loop through it getting the keys and values out at once
person = {&quot;name&quot;: &quot;Corina&quot;, &quot;age&quot;: 32, &quot;height&quot;: 1.4}

# This loops through and capitalizes the first letter of all keys
newPerson = {key.title(): value for key, value in person.items()}
print(list(newPerson.items()))</code></pre>
  </body>
</html>
